<script setup>
import { ref, computed, onMounted, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled, Upload, Check, ZoomIn, ZoomOut } from '@element-plus/icons-vue'
import { useUserProfileStore } from '@/store'
import provincesData from '@/data/province.json'
import citiesData from '@/data/city.json'
import { useRouter } from 'vue-router'
import AvatarUploader from '@/components/user/AvatarUploader.vue' // 导入新组件
import { baseURL } from '@/utils/request'

const router = useRouter()
const userProfileStore = useUserProfileStore()
const loading = ref(false)

// 直辖市ID列表
const directCities = ['110000000000', '120000000000', '310000000000', '500000000000']

// 激活的标签页
const activeTab = ref('basic')

// 用户个人资料
const userProfile = reactive({
  uuid: '',
  username: '',
  email: '',
  gender: 1, // 1: 男, 0: 女
  province: '',
  city: '',
  avatar: ''
})

// 地区显示文本
const locationDisplay = ref('')

// 添加计算属性判断用户是否已设置密码
const hasPassword = computed(() => userProfileStore.hasPassword())

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 设置初始密码表单（无需当前密码）
const setPasswordForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
}

// 表单验证规则 - 修改密码
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value === passwordForm.currentPassword) {
          callback(new Error('新密码不能与当前密码相同'));
        } else {
          callback();
        }
      }, 
      trigger: ['blur', 'change']
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 表单验证规则 - 设置初始密码
const setPasswordRules = {
  newPassword: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== setPasswordForm.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 地区选择器
const selectedRegion = ref([])
const regionOptions = computed(() => {
  return provincesData.map(province => {
    const provinceObj = {
      id: province.id,
      name: province.name,
      cities: []
    }
    
    // 特殊处理直辖市，让它们可以直接选择省级
    if (directCities.includes(province.id)) {
      provinceObj.leaf = true
    } 
    // 对于非直辖市，添加城市选项
    else if (citiesData[province.id]) {
      provinceObj.cities = citiesData[province.id].map(city => ({
        id: city.id,
        name: city.name
      }))
    }
    
    return provinceObj
  })
})

// 处理地区变化
const handleRegionChange = (value) => {
  if (!value || value.length === 0) {
    userProfile.province = ''
    userProfile.city = ''
    locationDisplay.value = ''
    return
  }
  
  // 设置省份ID
  userProfile.province = value[0]
  
  // 查找省份名称
  const province = provincesData.find(p => p.id === value[0])
  let displayText = province ? province.name : ''
  
  // 处理直辖市特殊情况
  if (directCities.includes(value[0])) {
    // 对于直辖市，自动设置城市为"市辖区"
    const cityData = citiesData[value[0]]
    if (cityData && cityData.length > 0) {
      userProfile.city = cityData[0].id
    }
    // 直辖市不显示市级名称，只显示省级（如：北京市）
  } 
  // 处理普通省份
  else if (value.length > 1) {
    userProfile.city = value[1]
    
    // 查找城市名称
    const cities = citiesData[value[0]] || []
    const city = cities.find(c => c.id === value[1])
    
    if (city) {
      displayText += '-' + city.name
    }
  } else {
    userProfile.city = ''
  }
  locationDisplay.value = displayText
}

// 表单引用
const profileForm = ref(null)
const passwordFormRef = ref(null)
const setPasswordFormRef = ref(null)

// 头像上传组件引用
const avatarUploaderRef = ref(null)

// 获取用户数据
const fetchUserData = async () => {
  try {
    // 如果store中已有用户数据则使用，否则重新获取
    if (!userProfileStore.userInfo.uuid) {
      await userProfileStore.fetchUserInfo()
    }
    
    const userInfo = userProfileStore.userInfo
    
    // 填充表单数据
    userProfile.uuid = userInfo.uuid
    userProfile.username = userInfo.username || '暂无用户名'
    userProfile.email = userInfo.email || ''
    userProfile.gender = userInfo.gender
    userProfile.avatar = `${baseURL}${userInfo.avatarUrl}`
    
    // 处理所在地区
    if (userInfo.province && userInfo.city) {
      // 如果已有省市ID数据
      userProfile.province = userInfo.province
      
      // 如果是直辖市，只选择省级
      if (directCities.includes(userInfo.province)) {
        selectedRegion.value = [userInfo.province]
      } else {
        // 普通省份选择省市两级
        selectedRegion.value = [userInfo.province, userInfo.city]
        userProfile.city = userInfo.city
      }
      
      // 触发一次变化处理来设置显示文本
      handleRegionChange(selectedRegion.value)
    } 
    // 如果没有省市ID但有location文本，尝试匹配对应的省市
    else if (userInfo.location) {
      locationDisplay.value = userInfo.location
      
      // 解析location获取省市信息
      const locationParts = userInfo.location.split('-')
      const provinceName = locationParts[0]
      const cityName = locationParts.length > 1 ? locationParts[1] : null
      
      // 查找匹配的省份
      const matchedProvince = provincesData.find(p => p.name === provinceName)
      if (matchedProvince) {
        userProfile.province = matchedProvince.id
        
        // 检查是否为直辖市
        if (directCities.includes(matchedProvince.id)) {
          selectedRegion.value = [matchedProvince.id]
          
          // 对于直辖市，自动设置城市为"市辖区"
          const cityData = citiesData[matchedProvince.id]
          if (cityData && cityData.length > 0) {
            userProfile.city = cityData[0].id
          }
        } 
        // 处理普通省份
        else if (cityName) {
          const cities = citiesData[matchedProvince.id] || []
          const matchedCity = cities.find(c => c.name === cityName)
          
          if (matchedCity) {
            userProfile.city = matchedCity.id
            selectedRegion.value = [matchedProvince.id, matchedCity.id]
          } else {
            // 如果找不到匹配的城市，只设置省份
            selectedRegion.value = [matchedProvince.id]
          }
        } else {
          // 没有城市信息，只设置省份
          selectedRegion.value = [matchedProvince.id]
        }
      }
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
    console.error('获取用户信息失败:', error)
  }
}

// 更新个人资料
const updateProfile = async () => {
  if (!profileForm.value) return
  
  await profileForm.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构建需要提交的用户数据
        const userData = {
          uuid: userProfile.uuid,
          username: userProfile.username,
          email: userProfile.email,
          gender: userProfile.gender,
          location: locationDisplay.value
        }
        
        if (await userProfileStore.updateProfile(userData)) {
          router.push('/user')
        }
      } catch (error) {
        console.error('更新个人资料失败:', error)
      }
    }
  })
}

// 处理更新密码
const updatePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 这里应该是调用API更新密码
        const passwordData = {
          uuid: userProfile.uuid,
          oldPassword: passwordForm.currentPassword,
          newPassword: passwordForm.newPassword
        }

        if (await userProfileStore.updatePassword(passwordData)) {
          router.push('/user')
        }
      } catch (error) {
        console.error('更新密码失败:', error)
      }
    }
  })
}

// 处理设置初始密码
const setInitialPassword = async () => {
  if (!setPasswordFormRef.value) return
  
  await setPasswordFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        loading.value = true
        const result = await userProfileStore.setPassword({
          username: userProfile.username,
          password: setPasswordForm.newPassword
        })
        
        if (result.status === 0) {
          // 密码设置成功后更新用户信息
          await userProfileStore.fetchUserInfo()
          resetForm('setPasswordFormRef')
        }
      } finally {
        loading.value = false
      }
    } else {
      console.log('验证失败', fields)
    }
  })
}

// 修改处理头像更新方法
const handleAvatarUpdate = async (avatarData) => {
  try {
    // 转换为 FormData
    const formData = new FormData()
    formData.append('uuid', userProfile.uuid)
    formData.append('avatarFile', avatarData.file)
    
    // 更新本地数据
    userProfile.avatar = avatarData.previewUrl

    // 更新store中的用户信息
    await userProfileStore.updateUserAvatar(formData)

    // 更新成功后返回用户个人页面
    router.push('/user')
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
    // 重置上传组件状态
    if (avatarUploaderRef.value) {
      avatarUploaderRef.value.isUploading = false
    }
  }
}

// 重置表单
const resetForm = (formName) => {
  if (formName === 'profileForm' && profileForm.value) {
    profileForm.value.resetFields()
  } else if (formName === 'setPasswordFormRef') {
    setPasswordForm.newPassword = ''
    setPasswordForm.confirmPassword = ''
    setPasswordFormRef.value.resetFields()
  } else if (formName === 'passwordFormRef') {
    passwordForm.currentPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
    passwordFormRef.value.resetFields()
  }
}

// 页面加载时获取用户数据
onMounted(() => {
  fetchUserData()
})
</script>

<template>
  <div class="edit-profile">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人资料设置</h2>
        </div>
      </template>
      
      <!-- 标签切换区域 -->
      <el-tabs v-model="activeTab" type="card" class="profile-tabs">
        <el-tab-pane label="基本资料" name="basic">
          <el-form ref="profileForm" :model="userProfile" label-width="100px" :rules="profileRules">
            <el-form-item label="用户ID">
              <el-input v-model="userProfile.uuid" disabled>
                <template #append>
                  <el-tooltip content="用户ID不可更改" placement="top">
                    <el-icon><InfoFilled /></el-icon>
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="用户名" prop="username">
              <el-input v-model="userProfile.username" placeholder="请输入用户名"></el-input>
            </el-form-item>

            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="userProfile.email" placeholder="请输入电子邮箱"></el-input>
            </el-form-item>

            <el-form-item label="性别">
              <el-radio-group v-model="userProfile.gender">
                <el-radio :value="1">男</el-radio>
                <el-radio :value="0">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="所在地区">
              <el-row :gutter="12">
                <el-col :span="16">
                  <el-cascader
                    v-model="selectedRegion"
                    :options="regionOptions"
                    :props="{ 
                      expandTrigger: 'hover',
                      value: 'id',
                      label: 'name',
                      children: 'cities',
                      checkStrictly: true
                    }"
                    placeholder="请选择所在地区"
                    @change="handleRegionChange"
                    clearable
                    style="width: 100%;">
                  </el-cascader>
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="updateProfile" class="netease-red-btn">保存更改</el-button>
              <el-button @click="resetForm('profileForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane v-if="hasPassword" label="修改密码" name="password">
          <el-form ref="passwordFormRef" :model="passwordForm" label-width="100px" :rules="passwordRules">
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input v-model="passwordForm.currentPassword" type="password" placeholder="请输入当前密码" show-password></el-input>
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password></el-input>
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="updatePassword" class="netease-red-btn">更新密码</el-button>
              <el-button @click="resetForm('passwordFormRef')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane v-else label="设置密码" name="password">
          <el-form ref="setPasswordFormRef" :model="setPasswordForm" label-width="100px" :rules="setPasswordRules">
            <div class="password-intro">
              <el-alert
                title="您尚未设置密码"
                type="info"
                description="设置密码后，可以使用用户名和密码登录您的账号，无需验证码"
                show-icon
                :closable="false"
                style="margin-bottom: 20px;"
              />
            </div>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="setPasswordForm.newPassword" type="password" placeholder="请设置密码" show-password></el-input>
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="setPasswordForm.confirmPassword" type="password" placeholder="请再次输入密码" show-password></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="setInitialPassword" class="netease-red-btn">设置密码</el-button>
              <el-button @click="resetForm('setPasswordFormRef')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="更改头像" name="avatar">
          <avatar-uploader 
            ref="avatarUploaderRef"
            :current-avatar="userProfileStore.userInfo.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
            @update="handleAvatarUpdate"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<style scoped>
.edit-profile {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.profile-card {
  border-radius: 8px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #333;
}

.netease-red-btn {
  background-color: #C20C0C !important;
  border-color: #C20C0C !important;
}

.netease-red-btn:hover,
.netease-red-btn:focus {
  background-color: #A70C0C !important;
  border-color: #A70C0C !important;
}

/* 修改Element-UI组件的主题色 */
:deep(.el-tabs__item.is-active) {
  color: #C20C0C;
}

:deep(.el-tabs__active-bar) {
  background-color: #C20C0C;
}

:deep(.el-tabs__item:hover) {
  color: #C20C0C;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  border-color: #C20C0C;
  background: #C20C0C;
}

:deep(.el-radio__input.is-checked+.el-radio__label) {
  color: #C20C0C;
}

:deep(.el-cascader__search-input) {
  border-color: #C20C0C;
}

:deep(.el-cascader__dropdown) {
  margin-top: 0;
}

/* 增强输入框的颜色和对比度 */
:deep(.el-input__inner) {
  color: #333333 !important; /* 使用更深的文本颜色 */
  font-weight: 400; /* 稍微加粗文本 */
}

:deep(.el-input__wrapper) {
  border-color: #d0d0d0; /* 稍微加深边框颜色 */
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #c20c0c inset !important; /* 使用网站主题红色作为焦点颜色 */
}

:deep(.el-select__wrapper) {
  color: #333333 !important;
}

:deep(.el-select .el-input__inner) {
  color: #333333 !important;
}

:deep(.el-cascader__label) {
  color: #333333 !important;
}

:deep(.el-textarea__inner) {
  color: #333333 !important;
}

/* 表单标签颜色也调整为更深的颜色 */
:deep(.el-form-item__label) {
  color: #333333 !important;
  font-weight: 500;
}

/* 针对下拉选择框中的文本颜色 */
:deep(.el-select-dropdown__item) {
  color: #333333;
}

:deep(.el-cascader-node__label) {
  color: #333333;
}

.avatar-page {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.avatar-upload-area {
  display: flex;
  align-items: center;
  gap: 15px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.upload-btn {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #333;
  padding: 6px 20px;
  font-size: 14px;
  border-radius: 4px;
}

.upload-btn:hover {
  border-color: #c0c4cc;
  color: #409eff;
}

.upload-info {
  color: #909399;
  font-size: 14px;
  margin-left: 10px;
}

.avatar-preview-area {
  display: flex;
  gap: 40px;
}

.main-preview {
  flex: 1;
}

.preview-box {
  position: relative;
  width: 400px;
  height: 400px;
  background-color: #fff; /* 改为白色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  border-radius: 0;
  border: none;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
}

.size-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.preview-title {
  font-size: 14px;
  font-weight: normal;
  color: #333;
  margin: 0 0 15px 0;
}

.large-preview, .small-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 15px;
}

.preview-image-container {
  width: 180px;
  height: 180px;
  background-color: #fff; /* 改为白色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  margin-bottom: 8px;
}

.preview-image-container.small {
  width: 40px;
  height: 40px;
}

.preview-image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.large-preview p, .small-preview p {
  color: #909399;
  font-size: 12px;
  margin: 0;
}

.preview-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  width: 100%;
  justify-content: center;
}

.cancel-btn {
  background-color: #f4f4f5;
  border-color: #dcdfe6;
  color: #606266;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .avatar-preview-area {
    flex-direction: column;
  }
  
  .preview-box {
    width: 100%;
    height: 300px;
  }
}

/* 新的裁剪框样式 - 可移动的框 */
.crop-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #fff;
}

.crop-image {
  display: block;
  max-width: 100%;
  max-height: 100%;
  margin: 0 auto;
}

.movable-crop-frame {
  position: absolute;
  border: 1px solid #fff;
  box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5);
  cursor: move;
  box-sizing: border-box;
}

/* 调整大小的手柄 */
.resize-handle {
  position: absolute;
  width: 14px;
  height: 14px;
  right: -7px;
  bottom: -7px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 50%;
  cursor: se-resize;
  z-index: 10;
}
</style> 